package com.chinairi.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinairi.common.model.BaseModel;
import com.chinairi.common.utils.UserSession;
import com.chinairi.mall.dao.*;
import com.chinairi.mall.error.BusinessException;
import com.chinairi.mall.error.EmBusinessError;
import com.chinairi.mall.model.*;
import com.chinairi.mall.service.ICancelOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 撤销订单实现类
 *
 * @author hmh
 * @date 2020/11/26
 */
@Service
public class CancelOrderServiceImpl extends ServiceImpl<CancelOrderMapper, CancelOrder> implements ICancelOrderService {

    private static final String AGREE_CANCEL = "1";
    private static final String REFUSE_CANCEL = "2";
    private static final String REMIND_AGREE_CANCEL = "3";
    private static final String REMIND_REFUSE_CANCEL = "4";

    @Autowired
    CancelOrderMapper cancelOrderMapper;

    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    OrderServicePurchaseMapper orderServicePurchaseMapper;

    @Autowired
    OrderServiceQualityMapper orderServiceQualityMapper;

    @Autowired
    OrderServiceStorageMapper orderServiceStorageMapper;

    @Autowired
    OrderServiceTransportMapper orderServiceTransportMapper;

    @Autowired
    OrderServiceSettleMapper orderServiceSettleMapper;

    /**
     * 新增撤销订单
     *
     * @param cancelOrder 撤销订单model
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void addCancelOrder(CancelOrder cancelOrder) {
        String userId = UserSession.getUserId();
        cancelOrder.setOcId(UUID.randomUUID().toString().replace("-", ""));
        cancelOrder.setCreater(UserSession.getLoginName());
        cancelOrder.setCreaterId(userId);
        cancelOrder.setCreateTime(new Date());
        try {
            OrderInfo orderInfo = orderInfoMapper.selectById(cancelOrder.getOrderId());
            cancelOrder.setReceiverId(orderInfo.getOrderShopId());
            cancelOrder.setReceiver(orderInfo.getOrderShopName());
            cancelOrder.setOldState(orderInfo.getOrderState());
        } catch (NullPointerException e) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "订单ID错误");
        }
        cancelOrder.setUpdateTime(new Date());
        cancelOrderMapper.add(cancelOrder);
    }

    /**
     * 批量添加服务商提醒
     *
     * @param serviceIdList 服务商id
     * @param cancelOrder   cancelOrder
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void batchInsertCancelOrder(List<?> serviceIdList, CancelOrder cancelOrder) {
        if (serviceIdList.size() > 0) {
            ArrayList<CancelOrder> cancelOrders = new ArrayList<>(serviceIdList.size());
            if (serviceIdList.get(0) instanceof OrderServiceTransport) {
                List<OrderServiceTransport> transports = (List<OrderServiceTransport>) serviceIdList;
                for (OrderServiceTransport service : transports) {
                    cancelOrders.add(new CancelOrder(UUID.randomUUID().toString().replace("-", ""), cancelOrder.getOrderId(), REMIND_AGREE_CANCEL, service.getOstState(), service.getOstShopId(), "",
                            cancelOrder.getCreaterId(), cancelOrder.getCreater(), cancelOrder.getTitle(), cancelOrder.getReason(), new Date(), new Date()));
                }
            }
            if (serviceIdList.get(0) instanceof OrderServiceQuality) {
                List<OrderServiceQuality> qualityList = (List<OrderServiceQuality>) serviceIdList;
                for (OrderServiceQuality service : qualityList) {
                    cancelOrders.add(new CancelOrder(UUID.randomUUID().toString().replace("-", ""), cancelOrder.getOrderId(), REMIND_AGREE_CANCEL, service.getOsqState(), service.getOsqShopId(), "",
                            cancelOrder.getCreaterId(), cancelOrder.getCreater(), cancelOrder.getTitle(), cancelOrder.getReason(), new Date(), new Date()));
                }
            }
            if (serviceIdList.get(0) instanceof OrderServicePurchase) {
                List<OrderServicePurchase> purchaseList = (List<OrderServicePurchase>) serviceIdList;
                for (OrderServicePurchase service : purchaseList) {
                    cancelOrders.add(new CancelOrder(UUID.randomUUID().toString().replace("-", ""), cancelOrder.getOrderId(), REMIND_AGREE_CANCEL, service.getOspState(), service.getOspShopId(), "",
                            cancelOrder.getCreaterId(), cancelOrder.getCreater(), cancelOrder.getTitle(), cancelOrder.getReason(), new Date(), new Date()));
                }
            }
            if (serviceIdList.get(0) instanceof OrderServiceSettle) {
                List<OrderServiceSettle> settles = (List<OrderServiceSettle>) serviceIdList;
                for (OrderServiceSettle service : settles) {
                    cancelOrders.add(new CancelOrder(UUID.randomUUID().toString().replace("-", ""), cancelOrder.getOrderId(), REMIND_AGREE_CANCEL, service.getOsseState(), service.getOsseShopId(), "",
                            cancelOrder.getCreaterId(), cancelOrder.getCreater(), cancelOrder.getTitle(), cancelOrder.getReason(), new Date(), new Date()));
                }
            }
            if (serviceIdList.get(0) instanceof OrderServiceStorage) {
                List<OrderServiceStorage> storages = (List<OrderServiceStorage>) serviceIdList;
                for (OrderServiceStorage service : storages) {
                    cancelOrders.add(new CancelOrder(UUID.randomUUID().toString().replace("-", ""), cancelOrder.getOrderId(), REMIND_AGREE_CANCEL, service.getOssState(), service.getOssShopId(), "",
                            cancelOrder.getCreaterId(), cancelOrder.getCreater(), cancelOrder.getTitle(), cancelOrder.getReason(), new Date(), new Date()));
                }
            }
            cancelOrderMapper.insertList(cancelOrders);
        }
    }

    /**
     * 确认撤销订单
     *
     * @param cancelOrder cancelOrder
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void confirmCancelOrder(CancelOrder cancelOrder) {
        //将订单下的服务订单状态修改为确认撤销状态
        confirmCancelOrder2(cancelOrder.getOrderId(), "3");
        //创建服务商通知
        List<OrderServiceTransport> transportList = orderServiceTransportMapper.getOstShopIdByOrderId(cancelOrder.getOrderId());
        List<OrderServicePurchase> purchaseList = orderServicePurchaseMapper.getOspShopIdByOrderId(cancelOrder.getOrderId());
        List<OrderServiceQuality> qualityList = orderServiceQualityMapper.getOsqShopIdByOrderId(cancelOrder.getOrderId());
        List<OrderServiceStorage> storageList = orderServiceStorageMapper.getOssShopIdByOrderId(cancelOrder.getOrderId());
        List<OrderServiceSettle> settleList = orderServiceSettleMapper.getOsseShopIdByOrderId(cancelOrder.getOrderId());
        batchInsertCancelOrder(transportList, cancelOrder);
        batchInsertCancelOrder(purchaseList, cancelOrder);
        batchInsertCancelOrder(qualityList, cancelOrder);
        batchInsertCancelOrder(storageList, cancelOrder);
        batchInsertCancelOrder(settleList, cancelOrder);
        //修改订单状态为确认撤销状态
        cancelOrderMapper.updateByOcId(cancelOrder.getOcId(), REMIND_AGREE_CANCEL);

    }

    /**
     * 拒绝撤销订单
     *
     * @param cancelOrder cancelOrder
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void refuseCancelOrder(CancelOrder cancelOrder) {
        //将订单下的服务订单状态修改为拒绝撤销状态
        confirmCancelOrder2(cancelOrder.getOrderId(), "5");
        //修改商品订单状态为拒绝撤销状态
        cancelOrderMapper.updateByOcId(cancelOrder.getOrderId(), REMIND_REFUSE_CANCEL);

    }

    /**
     * 修改订单下的服务订单状态
     *
     * @param orderId 订单id
     * @param state   修改的状态
     */
    @Transactional(rollbackFor = Exception.class)
    public void confirmCancelOrder2(String orderId, String state) {
        //根据订单id去查找该订单下的服务订单信息
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ORDER_ID", orderId);
        List<OrderServiceTransport> transportList = orderServiceTransportMapper.selectList(queryWrapper);
        List<OrderServicePurchase> purchaseList = orderServicePurchaseMapper.selectList(queryWrapper);
        List<OrderServiceQuality> qualityList = orderServiceQualityMapper.selectList(queryWrapper);
        List<OrderServiceStorage> storageList = orderServiceStorageMapper.selectList(queryWrapper);
        List<OrderServiceSettle> settleList = orderServiceSettleMapper.selectList(queryWrapper);
        //修改各个服务订单状态
        if (transportList.size() > 0) {
            transportList.forEach(orderServiceTransport -> orderServiceTransport.setOstState(state));
            transportList.forEach(orderServiceTransport -> orderServiceTransportMapper.updateById(orderServiceTransport));
        }
        if (purchaseList.size() > 0) {
            purchaseList.forEach(orderServicePurchase -> orderServicePurchase.setOspState(state));
            purchaseList.forEach(orderServicePurchase -> orderServicePurchaseMapper.updateById(orderServicePurchase));
        }
        if (qualityList.size() > 0) {
            qualityList.forEach(orderServiceQuality -> orderServiceQuality.setOsqState(state));
            qualityList.forEach(orderServiceQuality -> orderServiceQualityMapper.updateById(orderServiceQuality));
        }
        if (storageList.size() > 0) {
            storageList.forEach(orderServiceStorage -> orderServiceStorage.setOssState(state));
            storageList.forEach(orderServiceStorage -> orderServiceStorageMapper.updateById(orderServiceStorage));
        }
        if (settleList.size() > 0) {
            settleList.forEach(orderServiceSettle -> orderServiceSettle.setOsseState(state));
            settleList.forEach(orderServiceSettle -> orderServiceSettleMapper.updateById(orderServiceSettle));
        }
    }


    /**
     * 根据接收人id获得所有撤销订单信息
     *
     * @param receiverId 接受人id
     * @return 所有接收的撤销订单信息
     */
    @Override
    @Transactional(readOnly = true)
    public List<CancelOrder> getListByReceiverID(String receiverId) {
        return cancelOrderMapper.getListByReceiverId(receiverId);
    }

    /**
     * 根据创建者id获得创建的所有的撤销订单信息
     *
     * @param createrId 创建者id
     * @return 所有创建的撤销订单信息
     */
    @Override
    public List<CancelOrder> getListByCreaterID(String createrId) {
        return cancelOrderMapper.getListByCreatorId(createrId);
    }

    /**
     * 获得所有待确认的撤销订单信息
     *
     * @param receiverId 接收者id
     * @return 待确认订单列表
     */
    @Override
    public List<CancelOrder> getListPendingOrderByReceiverId(String receiverId) {
        return cancelOrderMapper.getListPendingOrderByReceiverId(receiverId);
    }

    /**
     * 根据接收者id查看所有的撤销订单提醒
     *
     * @param receiverId 接收者id
     * @return 所有的撤销订单提醒
     */
    @Override
    public List<CancelOrder> getRemindByReceiverId(String receiverId) {
        return cancelOrderMapper.getRemindListByReceiverId(receiverId);
    }
}
